<?php

namespace App\V3\V3_2_7\Services;

use App\V3\V3_2_7\Models\MaterielSpecTempModel;

class MaterielSpecTempService
{
    public static function add($data)
    {
        $id = MaterielSpecTempModel::query()->insertGetId($data);
        if(!empty($id)){
            return ['code'=>0,'msg'=>'success','data'=>$id];
        }else{
            return ['code'=>1,'msg'=>'创建失败！','data'=>''];
        }
    }

    public static function edit($condition,$data)
    {
        $bool = MaterielSpecTempModel::query()->where($condition)->update($data);
        if($bool)
            return ['code'=>0,'msg'=>'success','data'=>''];
        else
            return ['code'=>0,'msg'=>'修改失败！','data'=>''];
    }
    public static function del($condition)
    {
        $bool = MaterielSpecTempModel::query()->where($condition)->update(['delete_flag'=>1]);
        if($bool)
            return ['code'=>0,'msg'=>'success','data'=>''];
        else
            return ['code'=>0,'msg'=>'删除失败！','data'=>''];
    }
    public static function list($data,$idArr)
    {
        $materielSpecTempModel = MaterielSpecTempModel::query()
            ->where(['delete_flag'=>0,'main_id' => $data['main_id']]);
        if (!empty($idArr)) {
            $materielSpecTempModel->whereIn('id',$idArr);
        }
        $list = $materielSpecTempModel->orderBy('id', 'desc')->get();
        if (!empty($list)) {
            $list = $list->toArray();
            foreach ($list as $key=>$val) {
                $subArr = [];
                $masterArr = json_decode($val['master_spce_info'], true);
                if (!empty($val['master_spce_info']) && empty($val['sub_spce_info'])) {

                    $list[$key]['master_sub_spce_list'] = array_column($masterArr, 'spce_name');
                } elseif (!empty($val['master_spce_info']) && !empty($val['sub_spce_info'])) {
                    $subArr = json_decode($val['sub_spce_info'], true);
                    $spceList = [];
                    foreach ($masterArr as $mVal) {
                        foreach ($subArr as $sVal) {
                            $spceList[] = $mVal['spce_name'] . '-' . $sVal['spce_name'];
                        }
                    }
                    $list[$key]['master_sub_spce_list'] = $spceList;
                }

                $list[$key]['master_spce_info'] = $masterArr??[];
                $list[$key]['sub_spce_info'] = $subArr;
            }
        }
        return !empty($list)?$list:[];
    }
}
